package com.library.controller;

import com.library.entity.User;
import com.library.security.JwtTokenProvider;
import com.library.service.UserService;
import com.library.util.ResultUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器：处理登录请求
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private JwtTokenProvider jwtTokenProvider;

    @Resource
    private UserService userService;

    /**
     * 用户登录接口
     * @param loginRequest 包含用户名和密码的登录请求
     * @return 包含JWT令牌和用户信息的响应
     */
    @PostMapping("/login")
    public ResultUtil<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
        try {
            // 1. 进行身份认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );

            // 2. 将认证信息存入SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 3. 生成JWT令牌
            String jwt = jwtTokenProvider.generateToken(loginRequest.getUsername());

            // 4. 获取用户信息（不含密码）
            User user = userService.findByUsername(loginRequest.getUsername());
            if (user != null) {
                user.setPassword(null); // 清除密码，避免返回
            }

            // 5. 构建响应结果
            Map<String, Object> response = new HashMap<>();
            response.put("token", jwt);
            response.put("user", user);

            return ResultUtil.success(response);
        } catch (Exception e) {
            // 认证失败（用户名或密码错误）
            return ResultUtil.error("登录失败：用户名或密码不正确");
        }
    }

    /**
     * 登录请求参数封装类
     */
    public static class LoginRequest {
        private String username;
        private String password;

        // Getter和Setter
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}
